package com.wmg.aop;

import com.wmg.anno.RequireLogin;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * 采用AOP的方式处理权限问题。
 */
@Component
@Aspect
public class TestAop {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.wmg.controller.*.*(..))")
    public void aopMethod() {
    }

    @Around("aopMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AOP 鉴权 start");

        String methodName = joinPoint.getSignature().getName();
        Method method = getMethod(methodName, joinPoint);

        if (method.isAnnotationPresent(RequireLogin.class)) {
            log.info("被注解@RequireLogin修饰，判断是否登陆");
            RequireLogin requireLogin = method.getAnnotation(RequireLogin.class);
            log.info("拿到注解中的值 {}", requireLogin.value());
        }

        log.info("获取httpservletrequest");
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        log.info("获取request中的参数 {}", request.getParameterNames());

        log.info("AOP 鉴权 end");
        return joinPoint.proceed();
    }


    private Method getMethod(String name, JoinPoint joinPoint) {
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        Method realMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(name)) {
                realMethod = method;
                break;
            }
        }
        if (realMethod == null) {
            throw new RuntimeException("没有找到该方法");
        }
        return realMethod;
    }

}
